package com.cqjtu.drive.service.impl;

import com.cqjtu.drive.mapper.GradeMapper;
import com.cqjtu.drive.pojo.Grade;
import com.cqjtu.drive.response.Response;
import com.cqjtu.drive.service.GradeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class GradeServiceImpl implements GradeService {

    @Autowired
    private GradeMapper gradeMapper;

    @Override
    public Response<Grade> getGradeById(String sId) {
        Grade grade = gradeMapper.getGradeById(sId);
        if (grade != null) {
            return new Response<>(true, "Grade found", grade);
        } else {
            return new Response<>(false, "Grade not found");
        }
    }

    @Override
    public Response<String> insertGrade(Grade grade) {
        try {
            List<Grade> list = gradeMapper.getAllGrades();
            if(list != null && !list.isEmpty()){
                String id = Integer.toString(Integer.parseInt(list.get(list.size() - 1).getgId()) + 1);
                grade.setgId(id);
            }else {
                grade.setgId("1");
            }
            gradeMapper.insertGrade(grade);
            return new Response<>(true, "Grade inserted successfully");
        } catch (Exception e) {
            return new Response<>(false, "Failed to insert grade: " + e.getMessage());
        }
    }

    @Override
    public Response<String> updateGrade(Grade grade) {
        try {
            gradeMapper.updateGrade(grade);
            return new Response<>(true, "Grade updated successfully");
        } catch (Exception e) {
            return new Response<>(false, "Failed to update grade: " + e.getMessage());
        }
    }

    @Override
    public Response<String> deleteGrade(String sId) {
        try {
            gradeMapper.deleteGrade(sId);
            return new Response<>(true, "Grade deleted successfully");
        } catch (Exception e) {
            return new Response<>(false, "Failed to delete grade: " + e.getMessage());
        }
    }

    @Override
    public Response<List<Grade>> getAllGrades() {
        List<Grade> grades = gradeMapper.getAllGrades();
        if (grades != null && !grades.isEmpty()) {
            return new Response<>(true, "Grades retrieved successfully", grades);
        } else {
            return new Response<>(false, "No grades found");
        }
    }
}
